package com.teradata.feedProc.beans;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import gnu.trove.map.hash.TLongLongHashMap;

public class Cm11Lookup {
	// private static Map<Long, Long> lkpTable;
	private static TLongLongHashMap lkpTbl;

	public Cm11Lookup(String lkpFile) {
		
		populate(lkpFile);
	}
	
	//Will return the value of the tokenized key if it exists in the file, otherwise
	//return null
	public String LookUp(String key) {
		if(lkpTbl.contains(Long.parseLong(key))) {
			return Long.toString(lkpTbl.get(Long.parseLong(key)));
		}
		else {
			return "null";
		}
	}
	
	//Reads in all of the Cm values into memory to speed up the lookup process
	public static void populate(String lkpFile) {
		System.out.println("Reading in Lookup Table. Max memory that can be allocated:" + ((Runtime.getRuntime().maxMemory()) / (1024 * 1024)) + "M");

		System.out.println("At program start up - Total:" + ((Runtime.getRuntime().totalMemory() / (1024 * 1024))) + "M " + "Free:"
				+ ((Runtime.getRuntime().freeMemory()) / (1024 * 1024)) + "M " + "Used:" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024)
				+ "M ");

		int count = 0;
		String line;
		File file = new File(lkpFile);
		BufferedReader br;
		long[] l1 = new long[70000000];
		long[] l2 = new long[70000000];
		try {
			br = new BufferedReader(new FileReader(file));
			br.readLine();
			br.readLine();
			while ((line = br.readLine()) != null) {
				l1[count] = Long.parseLong(line.substring(0, 11));
				l2[count] = Long.parseLong(line.substring(12, 23));
				count++;
				line = null;
				//Every 30 million values, print out the memory usage
				if (count % 30000000 == 0) {
					System.out.println(count / 1000000);
					System.out.println("Total:" + ((Runtime.getRuntime().totalMemory() / (1024 * 1024))) + "M " + "Free:" + ((Runtime.getRuntime().freeMemory()) / (1024 * 1024))
							+ "M " + "Used:" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + "M ");
					System.out.println("----------------------------");
				}
			}
			lkpTbl = new TLongLongHashMap(l1, l2);
			System.out.println("Successfully loaded Lookup into hashmap");
			l1 = null;
			l2 = null;

		} catch (Exception e) {
			System.out.println("Trouble reading Cm11 Lookup Table -- " + e);
			System.exit(1);
		}
	}
}